'use client';

import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { DashboardLayout } from '@/components/layout/dashboard-layout';
import { AdminGuard } from '@/components/auth/PermissionGuard';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { toast } from '@/hooks/use-toast';
import { multiChainApi } from '@/lib/multi-chain-api';
import { API_ENDPOINTS } from '@/config/api';
import { useChain } from '@/context/ChainContext';
import {
  Plus,
  Edit,
  Trash2,
  Eye,
  Flag,
  Smartphone,
  Monitor,
  Users,
  BarChart3,
  Settings,
  Palette,
} from 'lucide-react';
import { formatNumber, formatDate } from '@/lib/utils';

interface DAppBanner {
  id: string;
  title: string;
  content: string;
  subtitle?: string;
  type: 'hero' | 'notification' | 'promotion' | 'warning' | 'image';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  display_location: 'top' | 'bottom' | 'floating';
  device_target: 'all' | 'desktop' | 'mobile';
  background_color?: string;
  text_color?: string;
  border_color?: string;
  button_text?: string;
  button_url?: string;
  button_color?: string;
  icon?: string;
  image_url?: string;
  is_dismissible: boolean;
  auto_dismiss_seconds?: number;
  show_close_button: boolean;
  start_date?: string;
  end_date?: string;
  target_all_users: boolean;
  target_user_levels?: string;
  target_miner_types?: string;
  target_wallet_addresses?: string;
  is_active: boolean;
  impression_count: number;
  click_count: number;
  dismiss_count: number;
  created_by: string;
  created_at: string;
  updated_at: string;
}

interface BannerStats {
  total_banners: number;
  active_banners: number;
  total_impressions: number;
  total_clicks: number;
  click_through_rate: number;
}

const BANNER_TYPES = [
  { value: 'hero', label: 'Hero Banner', color: 'bg-blue-100 text-blue-800' },
  { value: 'notification', label: 'Notification', color: 'bg-green-100 text-green-800' },
  { value: 'promotion', label: 'Promotion', color: 'bg-purple-100 text-purple-800' },
  { value: 'warning', label: 'Warning', color: 'bg-red-100 text-red-800' },
  { value: 'image', label: 'Image Only', color: 'bg-indigo-100 text-indigo-800' },
];

const PRIORITY_OPTIONS = [
  { value: 'low', label: 'Low', color: 'bg-gray-100 text-gray-800' },
  { value: 'medium', label: 'Medium', color: 'bg-yellow-100 text-yellow-800' },
  { value: 'high', label: 'High', color: 'bg-orange-100 text-orange-800' },
  { value: 'urgent', label: 'Urgent', color: 'bg-red-100 text-red-800' },
];

export default function BannersPage() {
  const { currentChain } = useChain();
  const queryClient = useQueryClient();
  
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showEditDialog, setShowEditDialog] = useState(false);
  const [selectedBanner, setSelectedBanner] = useState<DAppBanner | null>(null);
  const [showPreview, setShowPreview] = useState(false);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  
  // Form state
  const [formData, setFormData] = useState({
    title: '',
    content: '',
    subtitle: '',
    type: 'notification' as 'hero' | 'notification' | 'promotion' | 'warning' | 'image',
    priority: 'medium' as 'low' | 'medium' | 'high' | 'urgent',
    display_location: 'top' as 'top' | 'bottom' | 'floating',
    device_target: 'all' as 'all' | 'desktop' | 'mobile',
    background_color: '#3b82f6',
    text_color: '#ffffff',
    border_color: '#1e40af',
    button_text: '',
    button_url: '',
    button_color: '#10b981',
    image_url: '',
    is_dismissible: true,
    auto_dismiss_seconds: undefined as number | undefined,
    show_close_button: true,
    start_date: '',
    end_date: '',
    target_all_users: true,
    target_user_levels: '',
    target_miner_types: '',
    target_wallet_addresses: '',
  });

  // Fetch banner stats
  const { data: stats, isLoading: statsLoading } = useQuery<BannerStats>({
    queryKey: ['banner-stats', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.admin.banners.stats);
      return response.data;
    },
  });

  // Fetch all banners
  const { data: banners, isLoading: bannersLoading } = useQuery<DAppBanner[]>({
    queryKey: ['banners', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(API_ENDPOINTS.admin.banners.list);
      return response.data;
    },
  });

  // Create banner mutation
  const createBannerMutation = useMutation({
    mutationFn: async (bannerData: any) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.post(API_ENDPOINTS.admin.banners.create, bannerData);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['banners'] });
      queryClient.invalidateQueries({ queryKey: ['banner-stats'] });
      setShowCreateDialog(false);
      resetForm();
      toast({
        title: "Success",
        description: "Banner created successfully!",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to create banner",
        variant: "destructive",
      });
    },
  });

  // Update banner mutation
  const updateBannerMutation = useMutation({
    mutationFn: async ({ id, data }: { id: string; data: any }) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.put(API_ENDPOINTS.admin.banners.update(id), data);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['banners'] });
      queryClient.invalidateQueries({ queryKey: ['banner-stats'] });
      setShowEditDialog(false);
      setSelectedBanner(null);
      toast({
        title: "Success",
        description: "Banner updated successfully!",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to update banner",
        variant: "destructive",
      });
    },
  });

  // Delete banner mutation
  const deleteBannerMutation = useMutation({
    mutationFn: async (id: string) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.delete(API_ENDPOINTS.admin.banners.delete(id));
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['banners'] });
      queryClient.invalidateQueries({ queryKey: ['banner-stats'] });
      toast({
        title: "Success",
        description: "Banner deleted successfully!",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to delete banner",
        variant: "destructive",
      });
    },
  });

  // Toggle banner status mutation
  const toggleBannerMutation = useMutation({
    mutationFn: async (id: string) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.post(API_ENDPOINTS.admin.banners.toggle(id));
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['banners'] });
      queryClient.invalidateQueries({ queryKey: ['banner-stats'] });
      toast({
        title: "Success",
        description: "Banner status updated successfully!",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to update banner status",
        variant: "destructive",
      });
    },
  });

  const resetForm = () => {
    setFormData({
      title: '',
      content: '',
      subtitle: '',
      type: 'notification',
      priority: 'medium',
      display_location: 'top',
      device_target: 'all',
      background_color: '#3b82f6',
      text_color: '#ffffff',
      border_color: '#1e40af',
      button_text: '',
      button_url: '',
      button_color: '#10b981',
      image_url: '',
      is_dismissible: true,
      auto_dismiss_seconds: undefined,
      show_close_button: true,
      start_date: '',
      end_date: '',
      target_all_users: true,
      target_user_levels: '',
      target_miner_types: '',
      target_wallet_addresses: '',
    });
  };

  const handleCreate = () => {
    setShowCreateDialog(true);
    resetForm();
  };

  const handleEdit = (banner: DAppBanner) => {
    setSelectedBanner(banner);
    setFormData({
      title: banner.title,
      content: banner.content,
      subtitle: banner.subtitle || '',
      type: banner.type,
      priority: banner.priority,
      display_location: banner.display_location,
      device_target: banner.device_target,
      background_color: banner.background_color || '#3b82f6',
      text_color: banner.text_color || '#ffffff',
      border_color: banner.border_color || '#1e40af',
      button_text: banner.button_text || '',
      button_url: banner.button_url || '',
      button_color: banner.button_color || '#10b981',
      image_url: banner.image_url || '',
      is_dismissible: banner.is_dismissible,
      auto_dismiss_seconds: banner.auto_dismiss_seconds,
      show_close_button: banner.show_close_button,
      start_date: banner.start_date?.split('T')[0] || '',
      end_date: banner.end_date?.split('T')[0] || '',
      target_all_users: banner.target_all_users,
      target_user_levels: banner.target_user_levels || '',
      target_miner_types: banner.target_miner_types || '',
      target_wallet_addresses: banner.target_wallet_addresses || '',
    });
    setShowEditDialog(true);
  };

  const handleSubmit = (isEdit: boolean = false) => {
    // Clean up form data - remove undefined values and convert to null
    const cleanFormData = Object.fromEntries(
      Object.entries(formData).map(([key, value]) => [
        key,
        value === undefined ? null : value
      ])
    );

    const submitData = {
      ...cleanFormData,
      start_date: formData.start_date ? `${formData.start_date}T00:00:00Z` : null,
      end_date: formData.end_date ? `${formData.end_date}T23:59:59Z` : null,
    };

    if (isEdit && selectedBanner) {
      updateBannerMutation.mutate({ id: selectedBanner.id, data: submitData });
    } else {
      createBannerMutation.mutate(submitData);
    }
  };

  const handleDelete = (banner: DAppBanner) => {
    if (window.confirm(`Are you sure you want to delete the banner "${banner.title}"?`)) {
      deleteBannerMutation.mutate(banner.id);
    }
  };

  const handleToggleStatus = (banner: DAppBanner) => {
    toggleBannerMutation.mutate(banner.id);
  };

  const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // Validate file size (5MB max)
    const maxSize = 5 * 1024 * 1024; // 5MB
    if (file.size > maxSize) {
      toast({
        title: "Error",
        description: "File size too large. Maximum size is 5MB",
        variant: "destructive",
      });
      return;
    }

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(file.type)) {
      toast({
        title: "Error",
        description: "Invalid file type. Please upload JPG, PNG, GIF, or WebP images",
        variant: "destructive",
      });
      return;
    }

    setIsUploadingImage(true);

    try {
      const client = multiChainApi.getClient(currentChain);
      const formData = new FormData();
      formData.append('file', file);

      const response = await client.post(API_ENDPOINTS.admin.banners.uploadImage, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      // Update the image URL in form data
      setFormData(prev => ({
        ...prev,
        image_url: response.data.url
      }));

      toast({
        title: "Success",
        description: "Image uploaded successfully!",
      });

      // Clear the file input
      event.target.value = '';

    } catch (error: any) {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to upload image",
        variant: "destructive",
      });
    } finally {
      setIsUploadingImage(false);
    }
  };

  const getBannerTypeInfo = (type: string) => {
    return BANNER_TYPES.find(t => t.value === type) || BANNER_TYPES[1];
  };

  const getPriorityInfo = (priority: string) => {
    return PRIORITY_OPTIONS.find(p => p.value === priority) || PRIORITY_OPTIONS[1];
  };

  // Stats cards data
  const statsCards = [
    {
      title: 'Total Banners',
      value: stats?.total_banners || 0,
      icon: Flag,
      color: 'text-blue-600',
      bgColor: 'bg-blue-100',
    },
    {
      title: 'Active Banners',
      value: stats?.active_banners || 0,
      icon: Eye,
      color: 'text-green-600',
      bgColor: 'bg-green-100',
    },
    {
      title: 'Total Impressions',
      value: formatNumber(stats?.total_impressions || 0),
      icon: BarChart3,
      color: 'text-purple-600',
      bgColor: 'bg-purple-100',
    },
    {
      title: 'Click-Through Rate',
      value: `${(stats?.click_through_rate || 0).toFixed(1)}%`,
      icon: Users,
      color: 'text-orange-600',
      bgColor: 'bg-orange-100',
    },
  ];

  return (
    <DashboardLayout>
      <AdminGuard>
        <div className="space-y-6">
          {/* Page Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">DApp Banner Management</h1>
              <p className="text-gray-500">Manage banners displayed in the DApp</p>
            </div>
            <Button onClick={handleCreate} className="flex items-center gap-2">
              <Plus className="h-4 w-4" />
              Create Banner
            </Button>
          </div>

          {/* Stats Grid */}
          <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
            {statsCards.map((stat) => {
              const Icon = stat.icon;
              return (
                <Card key={stat.title}>
                  <CardContent className="p-6">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="text-sm font-medium text-gray-500">{stat.title}</p>
                        <p className="mt-2 text-3xl font-bold text-gray-900">
                          {stat.value}
                        </p>
                      </div>
                      <div className={`rounded-lg p-3 ${stat.bgColor}`}>
                        <Icon className={`h-6 w-6 ${stat.color}`} />
                      </div>
                    </div>
                  </CardContent>
                </Card>
              );
            })}
          </div>

          {/* Banners List */}
          <Card>
            <CardHeader>
              <CardTitle>All Banners</CardTitle>
            </CardHeader>
            <CardContent>
              {bannersLoading ? (
                <div className="flex items-center justify-center h-32">
                  <div className="text-sm text-gray-500">Loading banners...</div>
                </div>
              ) : banners && banners.length > 0 ? (
                <div className="space-y-4">
                  {banners.map((banner) => {
                    const typeInfo = getBannerTypeInfo(banner.type);
                    const priorityInfo = getPriorityInfo(banner.priority);
                    
                    return (
                      <div
                        key={banner.id}
                        className="border rounded-lg p-4 hover:bg-gray-50 transition-colors"
                      >
                        <div className="flex items-start justify-between">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-3 mb-2">
                              <h3 className="font-medium text-gray-900 truncate">
                                {banner.title}
                              </h3>
                              <Badge className={typeInfo.color}>
                                {typeInfo.label}
                              </Badge>
                              <Badge className={priorityInfo.color}>
                                {priorityInfo.label}
                              </Badge>
                              <Badge variant={banner.is_active ? "default" : "secondary"}>
                                {banner.is_active ? "Active" : "Inactive"}
                              </Badge>
                            </div>
                            <p className="text-sm text-gray-600 mb-2 line-clamp-2">
                              {banner.content}
                            </p>
                            <div className="flex items-center gap-4 text-xs text-gray-500">
                              <span className="flex items-center gap-1">
                                <Monitor className="h-3 w-3" />
                                {banner.device_target}
                              </span>
                              <span className="flex items-center gap-1">
                                <BarChart3 className="h-3 w-3" />
                                {formatNumber(banner.impression_count)} impressions
                              </span>
                              <span className="flex items-center gap-1">
                                <Users className="h-3 w-3" />
                                {formatNumber(banner.click_count)} clicks
                              </span>
                              <span>Updated: {formatDate(banner.updated_at)}</span>
                            </div>
                          </div>
                          <div className="flex items-center gap-2 ml-4">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleEdit(banner)}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleToggleStatus(banner)}
                            >
                              {banner.is_active ? 'Deactivate' : 'Activate'}
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => handleDelete(banner)}
                              className="text-red-600 hover:text-red-700"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <div className="text-center py-8">
                  <Flag className="mx-auto h-12 w-12 text-gray-400" />
                  <h3 className="mt-2 text-sm font-medium text-gray-900">No banners</h3>
                  <p className="mt-1 text-sm text-gray-500">
                    Get started by creating your first banner.
                  </p>
                  <div className="mt-6">
                    <Button onClick={handleCreate}>
                      <Plus className="h-4 w-4 mr-2" />
                      Create Banner
                    </Button>
                  </div>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Create/Edit Banner Dialog */}
          <Dialog open={showCreateDialog || showEditDialog} onOpenChange={(open) => {
            if (!open) {
              setShowCreateDialog(false);
              setShowEditDialog(false);
              setSelectedBanner(null);
            }
          }}>
            <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle>
                  {showEditDialog ? 'Edit Banner' : 'Create New Banner'}
                </DialogTitle>
                <DialogDescription>
                  {showEditDialog ? 'Modify the banner details below.' : 'Fill in the details to create a new banner.'}
                </DialogDescription>
              </DialogHeader>

              <div className="space-y-6">
                <Tabs defaultValue="content" className="w-full">
                  <TabsList className="grid w-full grid-cols-4">
                    <TabsTrigger value="content">Content</TabsTrigger>
                    <TabsTrigger value="styling">Styling</TabsTrigger>
                    <TabsTrigger value="behavior">Behavior</TabsTrigger>
                    <TabsTrigger value="targeting">Targeting</TabsTrigger>
                  </TabsList>

                  <TabsContent value="content" className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="title">Title *</Label>
                        <Input
                          id="title"
                          value={formData.title}
                          onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                          placeholder="Banner title"
                          required
                        />
                      </div>
                      <div>
                        <Label htmlFor="subtitle">Subtitle</Label>
                        <Input
                          id="subtitle"
                          value={formData.subtitle}
                          onChange={(e) => setFormData({ ...formData, subtitle: e.target.value })}
                          placeholder="Banner subtitle (optional)"
                        />
                      </div>
                    </div>
                    <div>
                      <Label htmlFor="content">Content *</Label>
                      <Textarea
                        id="content"
                        value={formData.content}
                        onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                        placeholder="Banner content"
                        rows={3}
                        required
                      />
                    </div>
                    {formData.type === 'image' && (
                      <div className="space-y-4">
                        <div>
                          <Label htmlFor="image_upload">Upload Image</Label>
                          <input
                            id="image_upload"
                            type="file"
                            accept="image/*"
                            onChange={handleImageUpload}
                            disabled={isUploadingImage}
                            className="w-full p-2 border border-gray-300 rounded-md focus:ring-indigo-500 focus:border-indigo-500 disabled:opacity-50"
                          />
                          <p className="text-xs text-gray-500 mt-1">
                            {isUploadingImage ? 'Uploading...' : 'Upload an image file (JPG, PNG, GIF, WebP) - max 5MB'}
                          </p>
                        </div>
                        <div className="text-center text-gray-500">or</div>
                        <div>
                          <Label htmlFor="image_url">Image URL *</Label>
                          <Input
                            id="image_url"
                            value={formData.image_url}
                            onChange={(e) => setFormData({ ...formData, image_url: e.target.value })}
                            placeholder="https://example.com/banner-image.jpg"
                            required={formData.type === 'image'}
                          />
                          <p className="text-xs text-gray-500 mt-1">
                            Or provide the URL of an existing image
                          </p>
                        </div>
                      </div>
                    )}
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="type">Type</Label>
                        <select
                          value={formData.type}
                          onChange={(e) => setFormData({ ...formData, type: e.target.value as any })}
                          className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        >
                          {BANNER_TYPES.map((type) => (
                            <option key={type.value} value={type.value}>
                              {type.label}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <Label htmlFor="priority">Priority</Label>
                        <select
                          value={formData.priority}
                          onChange={(e) => setFormData({ ...formData, priority: e.target.value as any })}
                          className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        >
                          {PRIORITY_OPTIONS.map((priority) => (
                            <option key={priority.value} value={priority.value}>
                              {priority.label}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                  </TabsContent>

                  <TabsContent value="styling" className="space-y-4">
                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <Label htmlFor="background_color">Background Color</Label>
                        <div className="flex items-center gap-2">
                          <Input
                            type="color"
                            id="background_color"
                            value={formData.background_color}
                            onChange={(e) => setFormData({ ...formData, background_color: e.target.value })}
                            className="w-12 h-8 p-1"
                          />
                          <Input
                            value={formData.background_color}
                            onChange={(e) => setFormData({ ...formData, background_color: e.target.value })}
                            placeholder="#3b82f6"
                          />
                        </div>
                      </div>
                      <div>
                        <Label htmlFor="text_color">Text Color</Label>
                        <div className="flex items-center gap-2">
                          <Input
                            type="color"
                            id="text_color"
                            value={formData.text_color}
                            onChange={(e) => setFormData({ ...formData, text_color: e.target.value })}
                            className="w-12 h-8 p-1"
                          />
                          <Input
                            value={formData.text_color}
                            onChange={(e) => setFormData({ ...formData, text_color: e.target.value })}
                            placeholder="#ffffff"
                          />
                        </div>
                      </div>
                      <div>
                        <Label htmlFor="border_color">Border Color</Label>
                        <div className="flex items-center gap-2">
                          <Input
                            type="color"
                            id="border_color"
                            value={formData.border_color}
                            onChange={(e) => setFormData({ ...formData, border_color: e.target.value })}
                            className="w-12 h-8 p-1"
                          />
                          <Input
                            value={formData.border_color}
                            onChange={(e) => setFormData({ ...formData, border_color: e.target.value })}
                            placeholder="#1e40af"
                          />
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="button_text">Button Text</Label>
                        <Input
                          id="button_text"
                          value={formData.button_text}
                          onChange={(e) => setFormData({ ...formData, button_text: e.target.value })}
                          placeholder="Learn More"
                        />
                      </div>
                      <div>
                        <Label htmlFor="button_url">Button URL</Label>
                        <Input
                          id="button_url"
                          value={formData.button_url}
                          onChange={(e) => setFormData({ ...formData, button_url: e.target.value })}
                          placeholder="https://example.com"
                        />
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="display_location">Display Location</Label>
                        <select
                          value={formData.display_location}
                          onChange={(e) => setFormData({ ...formData, display_location: e.target.value as any })}
                          className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        >
                          <option value="top">Top</option>
                          <option value="bottom">Bottom</option>
                          <option value="floating">Floating</option>
                        </select>
                      </div>
                      <div>
                        <Label htmlFor="device_target">Device Target</Label>
                        <select
                          value={formData.device_target}
                          onChange={(e) => setFormData({ ...formData, device_target: e.target.value as any })}
                          className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"
                        >
                          <option value="all">All Devices</option>
                          <option value="desktop">Desktop Only</option>
                          <option value="mobile">Mobile Only</option>
                        </select>
                      </div>
                    </div>
                  </TabsContent>

                  <TabsContent value="behavior" className="space-y-4">
                    <div className="flex items-center justify-between">
                      <Label htmlFor="is_dismissible">Dismissible</Label>
                      <Switch
                        id="is_dismissible"
                        checked={formData.is_dismissible}
                        onCheckedChange={(checked) => setFormData({ ...formData, is_dismissible: checked })}
                      />
                    </div>
                    <div className="flex items-center justify-between">
                      <Label htmlFor="show_close_button">Show Close Button</Label>
                      <Switch
                        id="show_close_button"
                        checked={formData.show_close_button}
                        onCheckedChange={(checked) => setFormData({ ...formData, show_close_button: checked })}
                      />
                    </div>
                    <div>
                      <Label htmlFor="auto_dismiss_seconds">Auto-dismiss (seconds)</Label>
                      <Input
                        type="number"
                        id="auto_dismiss_seconds"
                        value={formData.auto_dismiss_seconds || ''}
                        onChange={(e) => setFormData({ 
                          ...formData, 
                          auto_dismiss_seconds: e.target.value ? parseInt(e.target.value) : undefined 
                        })}
                        placeholder="Leave empty for no auto-dismiss"
                      />
                    </div>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="start_date">Start Date</Label>
                        <Input
                          type="date"
                          id="start_date"
                          value={formData.start_date}
                          onChange={(e) => setFormData({ ...formData, start_date: e.target.value })}
                        />
                      </div>
                      <div>
                        <Label htmlFor="end_date">End Date</Label>
                        <Input
                          type="date"
                          id="end_date"
                          value={formData.end_date}
                          onChange={(e) => setFormData({ ...formData, end_date: e.target.value })}
                        />
                      </div>
                    </div>
                  </TabsContent>

                  <TabsContent value="targeting" className="space-y-4">
                    <div className="flex items-center justify-between">
                      <Label htmlFor="target_all_users">Target All Users</Label>
                      <Switch
                        id="target_all_users"
                        checked={formData.target_all_users}
                        onCheckedChange={(checked) => setFormData({ ...formData, target_all_users: checked })}
                      />
                    </div>
                    {!formData.target_all_users && (
                      <>
                        <div>
                          <Label htmlFor="target_user_levels">Target User Levels</Label>
                          <Input
                            id="target_user_levels"
                            value={formData.target_user_levels}
                            onChange={(e) => setFormData({ ...formData, target_user_levels: e.target.value })}
                            placeholder="T0,T1,T2 (comma-separated)"
                          />
                        </div>
                        <div>
                          <Label htmlFor="target_miner_types">Target Miner Types</Label>
                          <Input
                            id="target_miner_types"
                            value={formData.target_miner_types}
                            onChange={(e) => setFormData({ ...formData, target_miner_types: e.target.value })}
                            placeholder="M0,M1,M2 (comma-separated)"
                          />
                        </div>
                        <div>
                          <Label htmlFor="target_wallet_addresses">Target Wallet Addresses</Label>
                          <Textarea
                            id="target_wallet_addresses"
                            value={formData.target_wallet_addresses}
                            onChange={(e) => setFormData({ ...formData, target_wallet_addresses: e.target.value })}
                            placeholder="0x123...,0x456... (comma-separated wallet addresses)"
                            rows={3}
                          />
                        </div>
                      </>
                    )}
                  </TabsContent>
                </Tabs>

                {/* Banner Preview */}
                <div className="border-t pt-4">
                  <h4 className="font-medium text-gray-900 mb-2">Preview</h4>
                  {formData.type === 'image' ? (
                    <div className="relative rounded-lg overflow-hidden border-2" style={{ borderColor: formData.border_color }}>
                      {formData.image_url ? (
                        <img 
                          src={formData.image_url} 
                          alt="Banner preview" 
                          className="w-full h-auto object-cover"
                          onError={(e) => {
                            e.currentTarget.src = 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 400 200"%3E%3Crect width="400" height="200" fill="%23e5e7eb"/%3E%3Ctext x="50%25" y="50%25" text-anchor="middle" dy=".3em" fill="%236b7280" font-family="sans-serif" font-size="16"%3EImage preview unavailable%3C/text%3E%3C/svg%3E';
                          }}
                        />
                      ) : (
                        <div className="bg-gray-200 h-48 flex items-center justify-center">
                          <span className="text-gray-500">Enter image URL to see preview</span>
                        </div>
                      )}
                      {formData.button_text && formData.button_url && (
                        <div className="absolute bottom-4 left-4 right-4">
                          <button
                            className="px-6 py-3 rounded font-medium shadow-lg"
                            style={{ backgroundColor: formData.button_color, color: '#ffffff' }}
                          >
                            {formData.button_text}
                          </button>
                        </div>
                      )}
                      {formData.show_close_button && (
                        <button className="absolute top-2 right-2 bg-white bg-opacity-80 rounded-full w-8 h-8 flex items-center justify-center text-gray-600 hover:bg-opacity-100">
                          ×
                        </button>
                      )}
                    </div>
                  ) : (
                    <div
                      className="p-4 rounded-lg border-2"
                      style={{
                        backgroundColor: formData.background_color,
                        color: formData.text_color,
                        borderColor: formData.border_color,
                      }}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <h3 className="font-semibold">{formData.title || 'Banner Title'}</h3>
                          {formData.subtitle && (
                            <p className="text-sm opacity-90 mt-1">{formData.subtitle}</p>
                          )}
                          <p className="mt-2">{formData.content || 'Banner content will appear here...'}</p>
                          {formData.button_text && (
                            <button
                              className="mt-3 px-4 py-2 rounded text-sm font-medium"
                              style={{ backgroundColor: formData.button_color }}
                            >
                              {formData.button_text}
                            </button>
                          )}
                        </div>
                        {formData.show_close_button && (
                          <button className="text-lg opacity-70 hover:opacity-100">×</button>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <DialogFooter>
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowCreateDialog(false);
                    setShowEditDialog(false);
                    setSelectedBanner(null);
                  }}
                >
                  Cancel
                </Button>
                <Button
                  onClick={() => handleSubmit(showEditDialog)}
                  disabled={createBannerMutation.isPending || updateBannerMutation.isPending}
                >
                  {showEditDialog ? 'Update Banner' : 'Create Banner'}
                </Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
        </div>
      </AdminGuard>
    </DashboardLayout>
  );
}